<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Main controller
 */
class Controller_File extends Controller_Template {
	protected $_template = 'other/master';

	/**
	 * List of documents
	 */
	public function indexAction($cat_id = -1) {
		if ($cat_id > -1) {
			Session::set('file_cat_id', intval($cat_id));
		} else if (Session::is('file_cat_id')) {
			$cat_id = intval(Session::get('file_cat_id'));
		} else {
			$cat_id = 0;
		}

		$this->template->content = View::factory('file/index')
			->set('cat_id', $cat_id)
			->set('cat_list', Category::getFullList(2))
			->set('file_list', File::getList($cat_id))
			->render();
	}

	/**
	 * List of documents (file browser)
	 */
	public function browserAction($cat_id = -1) {
		if ($cat_id > -1) {
			Session::set('file_cat_id', intval($cat_id));
		} else if (Session::is('file_cat_id')) {
			$cat_id = intval(Session::get('file_cat_id'));
		} else {
			$cat_id = 0;
		}
		$this->template = null;
		$view = View::factory('file/browser')
			->set('cat_id', $cat_id)
			->set('cat_list', Category::getFullList(2))
			->set('file_list', File::getList($cat_id));
		Output::body($view->render());
	}

	/**
	 * List of documents (file browser for tiny mce)
	 */
	public function browserTinyMceAction($cat_id = -1) {
		if ($cat_id > -1) {
			Session::set('file_cat_id', intval($cat_id));
		} else if (Session::is('file_cat_id')) {
			$cat_id = intval(Session::get('file_cat_id'));
		} else {
			$cat_id = 0;
		}

		$this->template = null;
		$view = View::factory('file/browsertinymce')
			->set('cat_id', $cat_id)
			->set('cat_list', Category::getFullList(2))
			->set('file_list', File::getList($cat_id));
		Output::body($view->render());
	}

	/**
	 * Insert file
	 */
	public function insertAction($error = -1) {
		if (Input::isPostBack()) {
			$new_file_id = 0;
			
			$upload = new Upload;
			$file_info = $upload->save('uploaded_file');
			if (!$file_info['uploaded_file'][0]['error']) {
				$new_file_name = $file_info['uploaded_file'][0]['file_name'];
				$thumb_file_name = '';
				
				$data = array();
				Query::data($data, 'name', $new_file_name, Query::DATA_STRING);
				Query::data($data, 'name_orig', $file_info['uploaded_file'][0]['orig_name'], Query::DATA_STRING);
				Query::data($data, 'size', $file_info['uploaded_file'][0]['size'], Query::DATA_INTEGER);
				Query::data($data, 'extension', $file_info['uploaded_file'][0]['extension'], Query::DATA_STRING);
				Query::data($data, 'status_id',Input::post('file_status_id'), Query::DATA_INTEGER);
				Query::data($data, 'insert_user_id', User::getId(), Query::DATA_INTEGER);
				Query::data($data, 'insert_time', time(), Query::DATA_INTEGER);

				$image = new Image(DATA_DIR . 'upload/' . $new_file_name);
				if ($image->isImage()) {
					$width = $image->getWidth();
					$height = $image->getHeight();
					$thumb_size = intval(Config::get('file_thumb_size'));
					
					Query::data($data, 'width', $width, Query::DATA_INTEGER);
					Query::data($data, 'height', $height, Query::DATA_INTEGER);

					if (($width > $thumb_size) || ($height > $thumb_size)) {
						$image->resizeTo($thumb_size);
						$thumb_info = pathinfo($image->save(null, null, '-thumb'));
						$thumb_file_name = $thumb_info['basename'];
						Query::data($data, 'name_thumb', $thumb_file_name, Query::DATA_STRING);
					}
					$image->clear();
				}
				
				$new_file_id = File::insert($data);
			}

			if ($new_file_id) {
				File::addToCategory($new_file_id, Input::post('file_cat_id'));
				Tools::redirect(BASE_URL . 'file/update/' . $new_file_id . '/-2');
			} else {
				Tools::redirect(CURRENT_URL . '1');
			}
		} else {
			$cat_id = 0;
			if (Session::is('file_cat_id')) {
				$cat_id = intval(Session::get('file_cat_id'));
			}
			
			$this->template->content = View::factory('file/insert')
				->set('error', $error)
				->set('cat_id', $cat_id)
				->render();
		}
	}

	/**
	 * Insert multiple files
	 */
	public function insertmAction() {
		$cat_id = 0;
		if (Session::is('file_cat_id')) {
			$cat_id = intval(Session::get('file_cat_id'));
		}
		
		if (Input::isPostBack()) {
			$filename = Input::get('file');
			if (empty($filename)) { $filename = ''; }

			$parameters = Input::get('param');
			if (empty($parameters)) { $parameters = ''; }

			$offset = Input::get('offset');
			if (empty($offset)) { $offset = 0; }

			$firstChunkVal = Input::get('first');
			$firstChunk = false;
			if (!empty($firstChunkVal) && (strtolower($firstChunkVal) == 'true')) {
				$firstChunk = true;
			}

			$lastChunkVal = Input::get('last');
			$lastChunk = false;
			if (!empty($lastChunkVal) && (strtolower($lastChunkVal) == 'true')) {
				$lastChunk = true;
			}

			$file_path = DATA_DIR . 'temp/' . $filename;

			if ($firstChunk && file_exists($file_path)) {
				unlink($file_path);
			}

			//Write the file content (for all chunks)
			if (($offset > 0) && file_exists($file_path)) {
				$file = fopen($file_path, 'a'); //Append to existing file
			} else {
				$file = fopen($file_path, 'w'); //Write new file
			}

			//Get posted file data
			$input = fopen("php://input", 'r');
			
			if (($file != null) && ($input != null)) {
				//Write data to file
				while ($data = fread($input, 1024)) {
					fwrite($file, $data);
				}

				fclose($file);
				fclose($input);
			}
			
			if ($lastChunk) {
				//You have access to the parameters in $parameters and the filename in $filename
				$new_file_id = 0;
				$fileinfo = pathinfo($filename);
				$new_file_name = File::getUniqueName($filename);
				$orig_file_name = $filename;
				$thumb_file_name = '';
				
				$data = array();
				Query::data($data, 'name', $new_file_name, Query::DATA_STRING);
				Query::data($data, 'name_orig', $orig_file_name, Query::DATA_STRING);
				Query::data($data, 'size', filesize($file_path), Query::DATA_INTEGER);
				Query::data($data, 'extension', strtolower($fileinfo['extension']), Query::DATA_STRING);
				Query::data($data, 'status_id', 1, Query::DATA_INTEGER);
				Query::data($data, 'insert_user_id', User::getId(), Query::DATA_INTEGER);
				Query::data($data, 'insert_time', time(), Query::DATA_INTEGER);

				$image = new Image(DATA_DIR . 'temp/' . $orig_file_name);
				if ($image->isImage()) {
					$width = $image->getWidth();
					$height = $image->getHeight();
					$thumb_size = intval(Config::get('file_thumb_size'));
					
					Query::data($data, 'width', $width, Query::DATA_INTEGER);
					Query::data($data, 'height', $height, Query::DATA_INTEGER);

					if (($width > $thumb_size) || ($height > $thumb_size)) {
						$image->resizeTo($thumb_size);
						$thumb_path = DATA_DIR . 'temp/' . $new_file_name;
						$thumb_info = pathinfo($image->save($thumb_path, null, '-thumb'));
						$thumb_file_name = $thumb_info['basename'];
						Query::data($data, 'name_thumb', $thumb_file_name, Query::DATA_STRING);
					}
					$image->clear();
				}
				
				$new_file_id = File::insert($data);

				if ($new_file_id) {
					$old_path = DATA_DIR . 'temp/' . $orig_file_name;
					$new_path = DATA_DIR . 'upload/' . $new_file_name;
					rename($old_path, $new_path);

					if (!empty($thumb_file_name)) {
						$old_path = DATA_DIR . 'temp/' . $thumb_file_name;
						$new_path = DATA_DIR . 'upload/' . $thumb_file_name;
						rename($old_path, $new_path);
					}

					File::addToCategory($new_file_id, $cat_id);
				}
			}
		} else {
			$this->template->content = View::factory('file/insertm')
				->set('cat_id', $cat_id)
				->set('cat_path', Category::getFullPath($cat_id))
				->render();
		}
	}

	/**
	 * Update file
	 */
	public function updateAction($id = 0, $error = -1) {
		if (Input::isPostBack()) {
			$data = array();
			Query::data($data, 'status_id', Input::post('doc_status_id'), Query::DATA_INTEGER);
			Query::data($data, 'update_user_id', User::getId(), Query::DATA_INTEGER);
			Query::data($data, 'update_time', time(), Query::DATA_INTEGER);

			if (File::update($id, $data)) {
				File::moveToCategory($id, Input::post('file_cat_id'));
				Tools::redirect(CURRENT_URL . $id . '/0');
			} else {
				Tools::redirect(CURRENT_URL . $id . '/1');
			}
		} else {
			$file_info = File::getInfo($id);
			$categories = File::inCategories($id);
			$cat_id = 0;
			if (count($categories) > 0) {
				$cat_id = $categories[0];
			}
			$this->template->content = View::factory('file/update')
				->set('error', $error)
				->set('cat_id', $cat_id)
				->set('info', $file_info)
				->render();
		}
	}

	public function deleteAction($file_id, $cat_id = 0, $error = -1) {
		if (Input::isPostBack()) {
			$delete_from = intval(Input::post('delete_from'));
			$delete_code = 0;
			if (1 == $delete_from) {
				$data = array();
				Query::data($data, 'status_id', 3, Query::DATA_INTEGER);
				Query::data($data, 'delete_user_id',  User::getId(), Query::DATA_INTEGER);
				Query::data($data, 'delete_time', time(), Query::DATA_INTEGER);

				if (!File::delete($file_id, $data)) {
					$delete_code = 1;
				}
			} else if (2 == $delete_from) {
				$cat_list = Input::post('delete_from_cats');
				foreach ($cat_list as $cat) {
					File::removeFromCategory($file_id, $cat);
				}
			}
			
			Tools::redirect(CURRENT_URL . $file_id . '/' . $cat_id . '/' . $delete_code);
		} else {
			$cat_list = array();
			$cats = File::inCategories($file_id);
			foreach ($cats as $cat) {
				$cat_list[] = array(
					'id' => $cat,
					'path' => Category::getFullPath($cat)
				);
			}

			$this->template->content = View::factory('file/delete')
				->set('error', $error)
				->set('cat_id', $cat_id)
				->set('info', File::getInfo($file_id , 'id,name'))
				->set('cat_list', $cat_list)
				->render();
		}
	}
	
	public function moveAction($file_id, $from_cat_id, $to_cat_id) {
		$this->template = null;
		if ($from_cat_id != $to_cat_id) {
			if ($to_cat_id > 0) {
				File::moveToCategory($file_id, $to_cat_id);
			} else {
				File::removeFromCategory($file_id, $from_cat_id);
			}
		}
		Output::body('0');
	}
}